package net.neptech.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.neptech.mapper.PatientMapper;
import net.neptech.mapper.UserMapper;
import net.neptech.mapper.UserPatientMapper;
import net.neptech.model.appointment.MedicalCase;
import net.neptech.model.sys.Patient;
import net.neptech.model.sys.User;
import net.neptech.model.sys.UserPatient;
import net.neptech.service.PatientService;
import net.neptech.vm.ResponseResult;
import net.neptech.vo.PatientVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PatientServiceImpl implements PatientService {

    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserPatientMapper userPatientMapper;

    @Override
    public ResponseResult<List<Patient>> getPatientByUserId(Long userId) {

        List<Patient> patientList = patientMapper.getPatientByUserId(userId);

        return ResponseResult.success(patientList);
    }

    @Override
    public List<PatientVo> getPatientByPatientIds(List<MedicalCase> medicalCaseList) {
        // 提取所有patientId
        List<Long> patientIds = medicalCaseList.stream()
                                               .map(MedicalCase::getPatientId)
                                               .distinct()
                                               .collect(Collectors.toList());

        // 如果patientIds为空，返回空列表
        if (patientIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 一次性查询所有患者
        List<Patient> patients = patientMapper.selectList(
                new LambdaQueryWrapper<Patient>()
                        .in(Patient::getPatientId, patientIds)
        );
        
        // 创建患者ID到患者信息的映射
        Map<Long, Patient> patientMap = patients.stream()
                .collect(Collectors.toMap(Patient::getPatientId, patient -> patient));
        
        // 按患者ID分组病历信息
        Map<Long, List<MedicalCase>> medicalCaseMap = medicalCaseList.stream()
                .collect(Collectors.groupingBy(MedicalCase::getPatientId));
        
        // 查询用户-患者关系
        List<UserPatient> userPatients = userPatientMapper.selectList(
                new LambdaQueryWrapper<UserPatient>()
                        .in(UserPatient::getPatientId, patientIds)
        );
        
        // 提取用户ID
        List<Long> userIds = userPatients.stream()
                .map(UserPatient::getUserId)
                .distinct()
                .collect(Collectors.toList());
        
        // 查询用户信息
        Map<Long, User> userMap = new HashMap<>();
        if (!userIds.isEmpty()) {
            List<User> users = userMapper.selectList(
                    new LambdaQueryWrapper<User>()
                            .in(User::getUserId, userIds)
            );
            userMap = users.stream()
                    .collect(Collectors.toMap(User::getUserId, user -> user));
        }
        
        // 创建患者ID到用户ID列表的映射
        Map<Long, List<Long>> patientToUserIdsMap = userPatients.stream()
                .collect(Collectors.groupingBy(
                        UserPatient::getPatientId,
                        Collectors.mapping(UserPatient::getUserId, Collectors.toList())
                ));
        
        // 构建PatientVo列表
        List<PatientVo> patientVoList = new ArrayList<>();
        for (Long patientId : patientIds) {
            PatientVo patientVo = new PatientVo();
            patientVo.setPatient(patientMap.get(patientId));
            patientVo.setMedicalCaseList(medicalCaseMap.get(patientId));
            
            // 设置用户信息列表
            List<Long> userIdList = patientToUserIdsMap.get(patientId);
            if (userIdList != null && !userIdList.isEmpty()) {
                List<User> userList = userIdList.stream()
                        .map(userMap::get)
                        .filter(user -> user != null)
                        .collect(Collectors.toList());
                patientVo.setUsers(userList);
            } else {
                patientVo.setUsers(new ArrayList<>());
            }
            
            patientVoList.add(patientVo);
        }
        
        return patientVoList;
    }
}
